package com.masterclient.app.widget;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.managerlibrary.Tools;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.WXSendCancelEvent;
import com.eoner.middlelib.eventbus.event.WXSendFailedEvent;
import com.eoner.middlelib.eventbus.event.WXSendSuccessEvent;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.masterclient.app.R;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * @auther hjian
 * @date 2020/6/7.
 */
public class ShareScreenDialog extends Dialog {

    @BindView(R.id.share_screen_root)
    RelativeLayout shareScreenRoor;
    @BindView(R.id.share_imageview)
    ImageView shareImageview;

    @BindView(R.id.save_screen_pic)
    ImageView saveScreenPic;
    @BindView(R.id.save_screen_qr)
    ImageView saveScreenQr;
    @BindView(R.id.save_screen_scroll)
    ScrollView saveScreenScroll;

    private Activity context;
    private String imageUrl;
    private int statusHeight; // px
    private Bitmap bitmapScreen;
    private RxPermissions rxPermissions;
    private RxBus rxBus;

    public ShareScreenDialog(@NonNull Activity context, int statusHeight) {
        super(context, R.style.MyDialog);
        this.context = context;
        this.statusHeight = statusHeight;
        rxBus = RxBus.$();
        rxPermissions = new RxPermissions(context);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        windowparams.width = ScreenUtils.getScreenWidth();
        windowparams.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        window.setAttributes(windowparams);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_share_screen);
        ButterKnife.bind(this);
        setCanceledOnTouchOutside(true);
        shareScreenRoor.setPadding(0, statusHeight,0,0);

    }

    @OnClick({ R.id.share_wx, R.id.share_pyq, R.id.share_pic, R.id.share_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share_close:
                dismiss();
                break;
            case R.id.share_wx:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    share(true);
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.share_pyq:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    share(false);
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.share_pic:
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions){
                    new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                            R.mipmap.icon_permission_storage, () -> requestPermissions()).show();
                }else {
                    savePic();
                }
                break;
        }
    }
    private static final String APP_ID = "wx8031a358899ba015";

    private void share(boolean isSession){
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!hasPermissions){
            new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                    R.mipmap.icon_permission_storage, () -> requestPermissions(isSession)).show();
        }else {
            savePic(isSession);
        }
    }

    private void requestPermissions(){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        ToastUtil.showToast("保存文件权限申请失败,无法保存图片");
                    }
                    dismiss();
                });
    }

    private void requestPermissions(boolean isSession){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic(isSession);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(context, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void savePic(){
        Bitmap bitmap = bitmapScreen;
        if (bitmap == null) return;
        boolean result = UIUtils.saveImageToGallery(context, bitmap);
        if (result) {
            ToastUtil.showToast("保存成功");
        } else {
            ToastUtil.showToast("保存失败");
        }
        bitmap.recycle();
    }

    private void savePic(boolean isSession){
        Bitmap bitmap = bitmapScreen;
        if (bitmap == null) return;
        String path = UIUtils.getSaveImagePath(context, bitmap);
        if (WeiXinManager.checkVersionValid(context) && WeiXinManager.checkAndroidNotBelowN()) {
            path = WeiXinManager.getFileUri(context, new File(path));
        }
        if (!TextUtils.isEmpty(path)) {
            wxSharePic("he" + System.currentTimeMillis(),isSession,bitmap, path);
        } else {
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
        }
        bitmap.recycle();
    }

    private void wxSharePic(String transaction,boolean isSession,Bitmap bitmap, String path) {
        //初始化WXImageObject和WXMediaMessage对象
        WXImageObject imageObject;
        if (!StringUtil.isBlank(path)) {
            imageObject = new WXImageObject();
            imageObject.imagePath = path;
        } else {
            imageObject = new WXImageObject(bitmap);
        }
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        //设置缩略图
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        bitmap.recycle();
        msg.thumbData = Utils.bmpToByteArray(scaledBitmap,false);
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = transaction + Long.toString(System.currentTimeMillis());
        req.message = msg;
        //表示发送给朋友圈  WXSceneTimeline  表示发送给朋友  WXSceneSession
        req.scene = isSession ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        //调用api接口发送数据到微信
        IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID);
        api.sendReq(req);
    }

    public void shareData(String imageUrl, String shareUrl){
        this.imageUrl = imageUrl;
        saveScreenQr.setImageBitmap(Tools.createQRImage(shareUrl, ScreenUtils.dp2px(68), ScreenUtils.dp2px(68)
                , BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)));

        Glide.with(context).load(imageUrl).apply(new RequestOptions()
                .error(R.color.transparent).placeholder(R.color.transparent)).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                saveScreenPic.setImageDrawable(resource);
                saveScreenScroll.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getBitmap(saveScreenScroll);
                    }
                },100);
            }
        });

    }

    public Bitmap toCompositeBitmap(Bitmap foreground) {
        int bgWidth = foreground.getWidth();
        int bgHeight = foreground.getHeight();
        Bitmap newbmp = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newbmp);
        cv.drawBitmap(foreground, 0, 0, null);
        cv.save();//保存
        return newbmp;
    }

    public Bitmap getBitmap(ScrollView scrollView) {

        int h = 0;
        Bitmap bitmap = null;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
//        Log.e("======getBitmap", h + "===" + scrollView.getWidth());
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        Drawable background = scrollView.getBackground();
        if (background instanceof ColorDrawable) {
            ColorDrawable colorDrawable = (ColorDrawable) background;
            int color = colorDrawable.getColor();
            canvas.drawColor(color);
        }
        scrollView.draw(canvas);
        bitmapScreen = toCompositeBitmap(bitmap);
        shareImageview.setImageBitmap(bitmapScreen);
        bitmap.recycle();
        return bitmap;
    }

    @Override
    public void show() {
        EventBusManager.register(this);
        super.show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        EventBusManager.unRegister(this);
    }

    /**
     * 成功
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendSuccess(WXSendSuccessEvent successEvent) {
        Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 取消
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendCancel(WXSendCancelEvent cancelEvent) {
        Toast.makeText(context, "分享取消", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 失败
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendFailed(WXSendFailedEvent failedEvent) {
        Toast.makeText(context, "分享失败", Toast.LENGTH_LONG).show();
        dismiss();
    }

}
